<template>
  <div class="container">
    <div class="action-area">
      <el-upload
          class="avatar-uploader"
          ref="uploadRef"
          :action="uploadUrl"
          :auto-upload="false"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-change="handleFileChange"
          :headers="headers"
          name="file"
          :disabled="isUploading"
      >
        <img
            v-if="imageUrl"
            :src="imageUrl"
            class="avatar"
        />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus/>
        </el-icon>
      </el-upload>

      <div class="button-group">
        <el-button
            v-if="imageUrl && !isChanging"
            type="danger"
            @click="deleteImage"
            :disabled="isUploading"
        >
          删除图片
        </el-button>

        <el-button
            v-if="imageUrl && !isChanging"
            type="primary"
            @click="startChangeImage"
            :disabled="isUploading"
        >
          更改图片
        </el-button>

        <el-button
            v-if="isChanging"
            type="primary"
            @click="confirmChange"
            :disabled="!selectedFile"
        >
          确认修改
        </el-button>

        <el-button
            v-if="!isUploaded && !isChanging"
            type="primary"
            class="upload-button"
            :disabled="!selectedFile"
            @click="submitUpload"
        >
          点击上传
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import axios from 'axios'

const uploadUrl = 'http://localhost:8080/upload/images'
const uploadRef = ref(null)
const imageUrl = ref('')
const selectedFile = ref(null)
const isUploading = ref(false)
const isUploaded = ref(false)
const isChanging = ref(false)
const fileKey = ref('')
const headers = {}

const beforeAvatarUpload = (file) => {
  const acceptTypes = ['image/jpeg', 'image/png', 'image/gif']
  const isValidType = acceptTypes.includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleFileChange = (file) => {
  selectedFile.value = file.raw
  imageUrl.value = URL.createObjectURL(file.raw)
}

const handleAvatarSuccess = (response) => {
  fileKey.value = response
  imageUrl.value = 'http://你的域名/' + response
  isUploading.value = false
  isUploaded.value = true
  ElMessage.success('上传成功')
}

const submitUpload = () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择文件')
    return
  }
  isUploading.value = true
  uploadRef.value.submit()
}

const deleteImage = async () => {
  try {
    await axios.delete('/upload/delete', {
      params: {fileName: fileKey.value},
    })
    imageUrl.value = ''
    fileKey.value = ''
    selectedFile.value = null
    isUploaded.value = false
    ElMessage.info('图片已删除')
  } catch (error) {
    ElMessage.error('图片删除失败，请重试')
  }
}

const startChangeImage = () => {
  isChanging.value = true
  uploadRef.value.$el.querySelector('input').click()
}

const confirmChange = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择新图片')
    return
  }
  try {
    await axios.delete('/upload/delete', {
      params: {fileName: fileKey.value},
    })
    submitUpload()
    isChanging.value = false
  } catch (error) {
    ElMessage.error('修改图片失败，请重试')
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  text-align: center;
}

.action-area {
  margin-top: 20px;
}

.avatar-uploader {
  margin-bottom: 20px;
}

.avatar-uploader .avatar {
  width: 300px;
  height: 300px;
  display: block;
  object-fit: cover;
  border-radius: 10px;
  border: 2px solid var(--el-border-color);
  margin: 0 auto;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin: 0 auto;
  width: 300px;
  height: 300px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 40px;
  color: #8c939d;
  width: 300px;
  height: 300px;
  text-align: center;
  line-height: 300px;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 15px;
}

.upload-button {
  display: inline-block;
}
</style>
